const { result } = require("./underscore")

const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}

const formatTodayYMDTime = (t) =>{
  var date = new Date();
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()

  return formatNumber(year) + "-" + formatNumber(month) + "-" + formatNumber(day);
}

const formatStandandTime = (t) =>{
  var date = new Date(t);
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return formatNumber(hour) + ":" + formatNumber(minute) + ":" + formatNumber(second);
}

const buf2string = (buffer) => {
  var arr = Array.prototype.map.call(new Uint8Array(buffer), x => x)
  return arr.map((char, i) => {
    return String.fromCharCode(char);
  }).join('');
}

const buf2stringEx = (arrayBuffer) => {
  let unit8Arr = new Uint8Array(arrayBuffer);
  let encodedString = String.fromCharCode.apply(null, unit8Arr),
  decodedString = decodeURIComponent(escape((encodedString)));//没有这一步中文会乱码
  console.log(decodedString);
}

const ab2hex = (buffer) => {
  var hexArr = Array.prototype.map.call(
    new Uint8Array(buffer),
    function (bit) {
      return ('00' + bit.toString(16)).slice(-2)
    }
  )
  return hexArr.join('');
}

const hexToAscii = (hexStr) => {
  let asciiStr = '';
  for(let i = 0; i < hexStr.length; i += 2) {
      asciiStr += String.fromCharCode(parseInt(hexStr.substr(i, 2), 16));
  }
  return asciiStr;
}

const hexToAscii2 = (hexStr) => {
  // 使用一个空数组来存储交换后的字符  
  let swappedArray = [];  
      
  // 遍历字符串，每次处理两个字符  
  for (let i = 0; i < hexStr.length; i += 4) {  
      // 获取当前的两个字符  
      let pair0 = hexStr.substr(i, 2);
      let pair1 = hexStr.substr(i + 2, 2);
      // 将这两个字符反转顺序后添加到数组中  
      swappedArray.push(pair1, pair0);  
  }  
    
  // 将数组转换回字符串  
  let swappedHexString = swappedArray.join('');  

  let asciiStr = '';
  for(let i = 0; i < swappedHexString.length; i += 2) {
    var hexChar = swappedHexString.substr(i, 2)
    if (hexChar == '00') {  
      continue;  
    }
    asciiStr += String.fromCharCode(parseInt(hexChar, 16));
  }
  return asciiStr;
}

const roleToString = (role) => {
  return role == 0 ? "一级用户" : "二级用户";
}

const stringToRole = (role) => {
  return role == "一级用户" ? 0 : 1;
}

const sleep = (s) => {
  return new Promise((resolve,reject)=>{
      setTimeout(() => {
          resolve(2);
      }, s)
  })
}

const uuid = function () {
  var s = [];
  var hexDigits = "0123456789abcdef";

  for (var i = 0; i < 36; i++) {
    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
  }

  s[14] = "4"; 
  s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);
  s[8] = s[13] = s[18] = s[23] = "-";
  var uuid = s.join("");

  return uuid
}

const hex2String = function(hexArray) {  
  // 使用 map 方法将每个十六进制数转换为字符串，并去掉前缀 '0x'  
  const hexStrings = hexArray.map(hex => hex.toString(16).toUpperCase().padStart(2, '0'));  
  // 使用 join 方法将字符串数组拼接成一个单一的字符串  
  const resultString = hexStrings.join('');  
  return resultString
}

const hexToBinaryString = function(hex) {  
  let decimal = parseInt(hex, 16);  
  let binary = decimal.toString(2);  
  let paddedBinary = binary.padStart(16, '0');  
  return paddedBinary;  
}  

const findTopAndBottomThree = function(arr) {
  // Step 1: Map each element to an object with its value and original index
  const indexedArr = arr.map((value, index) => ({ value, index }));

  // Step 2: Sort the array by value in ascending order
  indexedArr.sort((a, b) => a.value - b.value);

  // Step 3: Extract the smallest three and largest three elements
  const smallestThree = indexedArr.slice(0, 3);
  const largestThree = indexedArr.slice(-3).reverse();

  // Step 4: Map to get the required result format
  const result = {
      smallestThree: smallestThree.map(({ value, index }) => ({ value, index })),
      largestThree: largestThree.map(({ value, index }) => ({ value, index })),
  };

  return result;
}

const decimalToFixedByteArray = function(decimal, byteLength) {  
  const byteArray = new Array(byteLength).fill(0); // 创建一个填充了0的数组  
  let remaining = decimal;  
  let byteIndex = byteLength - 1; // 从数组的最后一个元素（最高有效字节）开始  

  while (remaining > 0 && byteIndex >= 0) {  
      // 获取当前字节的值（0-255）  
      byteArray[byteIndex] = remaining & 0xFF;  
      // 移除当前字节表示的值  
      remaining = (remaining >>> 8);  
      byteIndex--;  
  }  
 
  return byteArray;  
}

module.exports = {
  formatTime,
  buf2string,
  buf2stringEx,
  ab2hex,
  hexToAscii,
  hexToAscii2,
  roleToString,
  stringToRole,
  sleep,
  formatStandandTime,
  formatTodayYMDTime,
  uuid,
  hex2String,
  hexToBinaryString,
  findTopAndBottomThree,
  decimalToFixedByteArray
}